/**    
 * @Title: QuartzContextLoaderListener.java  
 * @Package cn.com.ytst.data.integration.job.quartz  
 * @Description: TODO(用一句话描述该文件做什么)  
 * @author yanhewei@vv.cc.com    
 * @date 2019年10月8日 下午3:36:06  
 * @version V1.0    
*/
package cn.com.ytst.data.integration.manager.job;

import java.beans.Introspector;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;


import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.CachedIntrospectionResults;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import cn.com.ytst.data.integration.util.SpringContextUtil;



/**
 * @ClassName: QuartzContextLoaderListener
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author yanhewei@vv.cc.com
 * @date 2019年10月8日 下午3:36:06
 * 
 */

@WebListener
public class QuartzContextLoaderListener implements ServletContextListener {

	private Logger logger = LoggerFactory.getLogger(QuartzContextLoaderListener.class);

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		CachedIntrospectionResults.acceptClassLoader(Thread.currentThread().getContextClassLoader());
	}

	/**
	 * 容器关闭时触发
	 * 
	 * @param sce
	 */
	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		/**
		 * SpringContextUtil是我实现的一个获取bean的工具类,网上有很多例子,就不写出来了
		 * 这里主要是把调度器Scheduler和线程池ExecutorService关闭
		 */
		ThreadPoolTaskExecutor threadpooltaskexecutor = SpringContextUtil.getBean("threadpooltaskexecutor",
				ThreadPoolTaskExecutor.class);
		Scheduler scheduler = SpringContextUtil.getBean("scheduler", Scheduler.class);

		if (scheduler != null) {
			try {
				if (scheduler.isStarted()) {
					scheduler.shutdown();
				}
			} catch (SchedulerException e) {
				logger.error("", e);
				throw new RuntimeException("定时容器关闭失败");
			}
		}
		threadpooltaskexecutor.shutdown();
		CachedIntrospectionResults.clearClassLoader(Thread.currentThread().getContextClassLoader());
		Introspector.flushCaches();
	}

}
